/**
 * 兼容各个浏览器，停止a标签默认事件
 * @param {} event
 */
function _stopDefasultEvent(event){
	if(event.preventDefault){
		event.preventDefault();
	}else{
		event.returnValue=false;
	}
};
/**
 * 处理菜单节点URL，如果有子，则迭代处理子节点
 * @param {} node
 */
Ccay.Layout.urlCache={};
Ccay.menuHandle=function(node){
	var children=node.children,target,Target=Ccay.Layout.Config.LeftMenu.Target;
	target=node.target || Target.self;
	//处理URL链接
	if(node.url){
		Ccay.Layout.urlCache[node.url]=node.siteNodeId;
		//node.click="_stopDefasultEvent(event);";
		if(target==Target.frame){
			node.target=Target.self;
			if(node.url.indexOf("?")>0){
				node.url="#!"+node.url+"&__target="+Target.frame;
			}else{
				node.url="#!"+node.url+"?__target="+Target.frame;
			}
		}else if(!/^http:|^https:|^\.|^\//.test(node.url)){
			if(node.url.indexOf("#!")==-1)
				node.url="#!"+node.url;
		}
	}
	
	if(children){
		node.hasChildren = true;
		for(var i=0,tempNode;tempNode=children[i];i++){
			tempNode.level = node.level + 1;
			Ccay.menuHandle(tempNode);
		}
	}else{
		node.hasChildren = false;
	}

};

/**@description 根据菜单定位情况刷新页面导航条 
 * 
 */
Ccay.Layout.refreshNavigationBar=function(node){
	//debugger;
//	var parents=Ccay.Layout.getRootParentByNode(node);
//	parents.push(node);
//	var html="";
//	$.each(parents,function(i){
//		var href="href=\"{0}\"".formatValue(this.url);
//		var tag= this.url ? "a" :"span"
//		if (i<parents.length-1)
//			html+=("<{0} "+href+">{1}</{2}> > ").formatValue(tag,this.name,tag);
//		else
//			html+=("<{0} "+href+">{1}</{2}> ").formatValue(tag,this.name,tag);
//	}); 
//	$("#ccay_page_nav").empty();
//	$("#ccay_page_nav").html(html);
//	Ccay.Layout.renderTitle(node);
//	$("#ccay_page_nav").find("a").click(function(){
//		Ccay.Page.forward($(this).prop("href"));
//	});
	
};

/**返回到某节点的祖先节点集合
 * @param {node} node
 * @return {node}
 */
Ccay.Layout.getRootParentByNode= function(node){
	if(!node.getParentNode) return [];
	var parents=[],currNode=node;
	while(currNode=currNode.getParentNode()){
		parents.push(currNode);
	}
	parents.reverse();
	return parents;
};
///**通过点击节点或展开收缩标签进入该事件
// * @param {node} node 事件触发的节点
// * @param {boolean} isExpand 是否是点击展开收缩标签触发该事件
// */
//Ccay.Layout.refreshLeftMenu=function(node,isExpand){
//	var tree=$("#leftSiteMapTree").getCcayTreeManager();
//	var parents=Ccay.Layout.getRootParentByNode(node);
//	var rNode= parents.length>0 ? parents[0]:node;
//    $.each(Ccay.Layout.treeData,function(){
//    	var tempNode=tree.getNodeByParam("siteNodeId",this.siteNodeId);
//    	if(tempNode.siteNodeId!=rNode.siteNodeId && tempNode.open){
//    		tree.expandNode(tempNode,false,true);
//    	}
//    }) 
//    if(node.isParent && !isExpand){
//    	tree.expandNode(node);
//	}
//	Ccay.Layout.refreshScroller();
//	
//};
//如果
Ccay.Init.AfterUI.add(function(){
	
	//	var htmls = ['<DIV id=filter_leftSiteMapTree  class=ccay-tree-filter>',
	//		'<INPUT id="filterInput_leftSiteMapTree" style="width:100%" maxLength=100 type=text ></div>',
	//		'<div id="nanoscroller" class="nano"><div  class="content"><ul id="leftSiteMapTree"  ></ul></div></div>'
	//	];
	//	if( workspaceVO.config.IsFixedMenu && workspaceVO.config.IsFixedMenu != 0 && $("#leftSiteMapTree").length){
	//		$("#leftMenuContent").html(htmls.join(""))
	//	}
});

Ccay.Layout.initMenuScroll = function(){
	if( workspaceVO.config.IsFixedMenu && workspaceVO.config.IsFixedMenu != 0 && $("#leftSiteMapTree").length){
		Ccay.UI.Resizes.add(function(){
			Ccay.Layout.refreshScroller();
		});
		$(document.body).id("bodyfixed");
		var treeSettings = $("#leftSiteMapTree").getCcayTreeManager().setting;
		var winHeight = window.innerHeight ||document.documentElement.clientHeight;
		Ccay.Layout.refreshScroller();
		treeSettings.callback.onExpand = treeSettings.callback.onCollapse =function(){
			Ccay.Layout.refreshScroller();
		} 
		//阻止鼠标滚动冒泡
	
		$("#nanoscroller").bind("mousewheel",function(e){
			var panel = $(this).children(".content"),scrollTop = panel.scrollTop(),
	        		detail = e.originalEvent.wheelDelta,
	        		height = $("#leftSiteMapTree").height() -  panel.height();
	        	if($("#leftSiteMapTree").height() <= $("#leftSiteMapTree").parent().height()){
	        		return true;
	        	}
				if(scrollTop <= 0 && detail > 0){
					return false;
				}
				if(scrollTop + panel.height() - $("#leftSiteMapTree").height() > 0 && detail < 0 )
					return false;
					 
	     });

	   
	}
}

Ccay.Layout.refreshScroller = function(){
	if( workspaceVO.config.IsFixedMenu && workspaceVO.config.IsFixedMenu != 0 && $("#leftSiteMapTree").length){
		var winHeight = window.innerHeight ||document.documentElement.clientHeight;
		var top = $("#c_layout").position().top +  parseInt($("#c_layout").css("margin-top")), fixHeight = top +  ( $("#foot_div").is(":visible") ? $("#foot_div").height() : 0);
		$("#leftMenuContent").css("top",top); 
		$("#leftMenuContent").height(parseInt(winHeight) - fixHeight - 5);
		var margin = 40;
		
		$("#nanoscroller").height(parseInt(winHeight) - fixHeight - margin).nanoScroller();
		$("#ccayMainPanel").css("padding-bottom",  $("#foot_div").height());
		$("#leftSiteMapTree").parent().css("height","");
		
	} 
	setTimeout(function(){
		$("#c_layout").css("min-height",$("#leftMenuContent").height());
	})
	
}
Ccay.Init.Complete.add(Ccay.Layout.initMenuScroll);


/**通过当前URL得到指定节点，并选中该节点
 *@return {Object} node
 */
Ccay.Layout.selectMenuByUrl=function(){
	var requests = Ccay.Page.getRequest(),
		url = window.location.href,
		locatedUrl = url.split("#!")[1] || "",
		node;
	//无跳转的url时，选中首页节点
	if(!locatedUrl){
		var homeNode = workspaceVO.leftMenuNode;
		Ccay.Layout.selectNode(homeNode);
		Ccay.Layout.refreshNavigationBar(homeNode);
	    return;
	}
	// 1、根据ulr请求ccayNode参数定位
	var ccayNode = requests.ccayNode ;
	if(ccayNode){
		node = Ccay.Layout.findMenuNodeByAttr(workspaceVO.leftMenuNode,ccayNode,"location");
	    if(node){
	    	Ccay.Layout.selectNode(node);
	    	Ccay.Layout.refreshNavigationBar(node);
	    	Ccay.Layout.refreshScroller();
	    	return;
	    }
	};
	// 2、根据Url定位
	if(url.indexOf("#!") > 0){
		url = locatedUrl;
	}
	var siteNodeId = Ccay.Layout.getCacheId(url);
	if(siteNodeId){
		// 根据url定位
		node = Ccay.Layout.findMenuNodeByAttr(workspaceVO.leftMenuNode,siteNodeId);
	    if(!node){
	    	var isExistsParam = url.indexOf("?");
	    	if(isExistsParam>0){
	    		node = Ccay.Layout.findMenuNodeByAttr(workspaceVO.leftMenuNode,"#!" + url.substring(0,isExistsParam),"url");
	    	}
	    }
	    
	    if(node){
	    	Ccay.Layout.selectNode(node);
	    	Ccay.Layout.refreshNavigationBar(node);
	    	Ccay.Layout.refreshScroller();
	    }
	}
};

Ccay.Layout.getCacheId=function(url){
	Ccay.Core.log("find nodeId by url:"+url);
	if(url){
		var index=url.lastIndexOf("&");
		index<0 && (index=url.lastIndexOf("?"));
		if(index>0){
			return Ccay.Layout.urlCache[url] || Ccay.Layout.getCacheId(url.substring(0,index));
		}else{
			return Ccay.Layout.urlCache[url] ;
		}
	}
}

/**
 * @description 初始化页面上的角色切换 下拉框控件
 *@author chaowangbang
 *@since 2012-10-26
 */
Ccay.Layout.renderRoleSelect=function(){
//    	var user = Ccay.WorkspaceVO.user , 
//    			judg = workspaceVO.config.MergePermission2CurrentRole * 1;
//    	if(!judg){
//			var selecter = new Array();
//			selecter.push("<span>{0}</span>：".formatValue($i18n("ccay.home.label.currrole")));
//			selecter.push("<select id='currentrole' name='currentrole' onchange='Ccay.Permission.changeRole($(this).val());'>");
//				var currentRole = user.currentRole.roleId;
//				$.each( user.validRoles, function(i, roleVO){
//	  				var option = (roleVO.roleId === currentRole)?
//	  				("<option value='${roleId}' selected>${roleName}</option>").formatField(roleVO):
//	  				("<option value='${roleId}'>${roleName}</option>").formatField(roleVO);
//	  				selecter.push(option);
//			});
//			selecter.push("</select>"); 
//			$("#s_switch_role").append(selecter.join(" "));
//    	}else {
//    		$("#s_switch_role").hide();
//    	}
};

/**
 * 渲染初始化方法 header&foot 一体化
 *@author chaowangbang
 *@since 2012-10-26
 */
Ccay.Layout.renderHeader=function(){
	if(workspaceVO.user){
		$("#CURRENT_USER").text(workspaceVO.user.name);
		$("#loginoutmenu").html('<a href="./logout">Logout</a>');
		$("#loginoutbtn").html('<a href="./logout"><i class="fa fa-sign-in"></i>Log out</a>');
	}else{
		$("#CURRENT_USER").text("anonymous");
	}
//	$("#firstLoading").remove();
//	var setting=Ccay.Layout.Config.W3MenuSettings;
//	
//	if(!workspaceVO.switchLanguageEnabled){
//		delete setting.switch_lan;
//	}
//	setting.mylinks = false;
//	setting.app_setting.en.name=setting.app_setting.cn.name=$i18n("app.common.label.applicationName");
//	setting.lan_parameter= {default_lan: Ccay.Local.getCurrLanguage(true)},
//	window.w3 && w3.inner.ui.init(setting);
//	var tempdom=$(".W3AppTop_gray_Bar_Content_right >ul >li:eq({0})".formatValue(workspaceVO.switchLanguageEnabled ? 4 : 3));
//	!tempdom.length && (tempdom=$(".W3AppTop_gray_Bar_Content_right >ul >li:last"));
//	var liFullScreen=$("<li><span class='W3AppTop_dot'><a id='fullScreen_a'  href='javascript:Ccay.Common.toggleScreen();'>{0}</a></span></li>".formatValue($i18n("ccay.home.label.fullscreen")));
//	tempdom.before(liFullScreen);
//	if(workspaceVO.switchLanguageEnabled){
//		var languageItem=$("#W3AppTop_Container a[href*='Ccay.Local.changeLanguage']").parent();
//		var languageArray = [],languageList = Ccay.Format.getLangugaeList();
//		for(var i=0;len=languageList.length,i<len;i++){
//			languageArray.push('<option value="{0}" {1}>{2}</option>'.formatValue(languageList[i].id,languageList[i].id==workspaceVO.currentLanguage?'selected="selected"':"",$i18n(languageList[i].text)));
//		}
//		languageItem.html('<select onchange="Ccay.Local.changeLanguage(this.value)">'+languageArray.join("")+'</select>');
//	}
};

/**
 * 生成语种隐藏专用的Class并添加到Header
 */
Ccay.Layout.renderLanguageCSS = function(){
	$("head").append(Ccay.Local.getCurrLanguage() == "en_US"?
			"<style type='text/css'>.zh_CN {display:none}</style>":"<style type='text/css'>.en_US {display:none}</style>");
};

/**
 *@description 左菜单渲染初始化
 *@author chaowangbang
 *@since 2012-10-26
 */
Ccay.Layout.renderMenu=function(root,navigation){
	Ccay.UI.loading();
	Ccay.Layout.navigation = navigation;
	//禁止后退键  作用于IE、Chrome
	$(document).bind("keydown",function(e){
		 Ccay.Core.forbidBackSpace(e);
	})
	//禁止后退键 作用于Firefox、Opera
	$(document).bind("keypress",function(e){
		 Ccay.Core.forbidBackSpace(e);
	})
	
	Ccay.Page.homePath=root.url;
	
	//开始构建菜单
	//1、处理数据结构
	//1-1 构建一个没有子元素的root节点代表首页，一便渲染出首页节点
	var houmeNode = {
		name : root.name,
		siteNodeId : root.siteNodeId,
		target : "_self",
		url : root.url,
		faName:"home"
	}
	root.children = [houmeNode].concat(root.children);
	root.level = 0
	//1-2 处理每个节点属性
	Ccay.menuHandle(root);
	
	//2、生成HTML菜单
	if(root.children){
		var html = "";
		for(var i=0,tempNode;tempNode=root.children[i];i++){
			html += Ccay.Layout.createMenuTree(tempNode);
		}
		Ccay.Layout.renderMenuTree(html);
	}
	

	
//	$("#midPanel").bind("click",function(){
//		var leftpanel = $("#leftPanel").toggle();
//		var narrow = $("#menuHideNarrow").toggleClass('narrow');
//		Ccay.UI.Resizes.fire("menu");
//	});
//
//	var setting={
//		filter:"#filterInput_leftSiteMapTree",
//		urlMode:true,
//		onClick: function(event, treeId, treeNode){
//				$("#globalloading").remove();
//				var Target=Ccay.Layout.Config.LeftMenu.Target,target=treeNode.target,url;
//				if(treeNode.url && treeNode.url.length>2){
//					//if判断是否为点击节点为当前节点
//					if(treeNode.url==window.location.hash){
//						Ccay.Page.forward(treeNode.url);
//					}else{
//						if(target==Target.self){
//							if(treeNode.url.indexOf("#!")==0){
//								Ccay.Page.forward(treeNode.url.substring(2));
//								Ccay.Layout.renderTitle(treeNode);
//							}else{
//								window.location=treeNode.url;
//							}
//						}else if(target==Target.blank){
//							Ccay.Layout.selectMenuByUrl();
//							window.open(treeNode.url).focus();
//							return;
//						}else if(target==Target.frame){
//						}else{
//							Ccay.Layout.selectMenuByUrl();
//							window.open(treeNode.url,target);
//							return;
//						}
//					}
//				}
//				Ccay.Layout.refreshLeftMenu(treeNode); 
//		},
//		beforeExpand:function(treeId, treeNode){
//			Ccay.Layout.refreshLeftMenu(treeNode,true);
//		}
//	 }
//	var root=workspaceVO.leftMenuNode;
//	Ccay.Page.homePath=root.url;
//	Ccay.menuHandle(root);
//	/**
//	 * pengmingxing wx219318
//	 * 2014-06-20
//	 * 标题添加首页链接
//	 */
//	var W3AppTop_Header_title_app = $("#W3AppTop_Header .W3AppTop_Header_title_app");
//	var title_link = $('<a style="color:inherit;font-size:inherit;font-weight:inherit;text-decoration:none;"></a>').text(W3AppTop_Header_title_app.text()).attr("href",root.url);
//	title_link.click(function(){
//		var tree = $("#leftSiteMapTree").getCcayTreeManager();
//		if(tree && tree.selectNode){
//			tree.selectNode(tree.getNodes()[0], false);
//		}
//		Ccay.Layout.refreshNavigationBar(workspaceVO.leftMenuNode);
//	});
//	W3AppTop_Header_title_app.html(title_link);
//	
//	var index=location.href.indexOf("#!");
//	if(index<0 || index==location.href.length-2){
//		try{
//			if(workspaceVO.user.currentRole.defaultUrl){
//				Ccay.Page.forward(workspaceVO.user.currentRole.defaultUrl);
//			}
//		}catch(e){};
//	}
//	$("#ccay_page_nav").html("<a href='{0}'>{1}</a> >".formatValue(root.url,root.name));
//	
//	if(root.children){
//		var home=[{name:root.name,url:root.url,target:root.target,click:"_stopDefasultEvent(event);"}];
//		home=home.concat(root.children);
//		Ccay.Layout.treeData=root.children;
//		//菜单整行点击
//		$("#leftSiteMapTree").delegate("li","click",function(e){
//			if(e.target.tagName.toLowerCase()!="li"){
//				return;
//			}
//			$(this).children("a:first").click();
//			e.stopPropagation();
//		}).delegate("li","mouseover",function(e){
//			$(this).addClass("li_mouseover");
//			e.stopPropagation();
//		}).delegate("li","mouseout",function(e){
//			$(this).removeClass("li_mouseover");
//			e.stopPropagation();
//		});
//		$("#leftSiteMapTree").ccayTree(home,setting);
//	};
	
	
};

/**
 * @description 渲染导航菜单
 * @param treeNode 已生成的菜单HTML
 * @author chaowangbang
 * @since 2017-10-06
 */
Ccay.Layout.renderMenuTree = function(html){
	Ccay.Layout.navigation.append(html);
	Ccay.Layout.navigation.metisMenu();
	//菜单整行点击
	Ccay.Layout.navigation.delegate("li","click",function(e){
		if(e.target.tagName.toLowerCase()!="li"){
			return;
		}
		$(this).children("a:first").click();
	})
}

/**
 * @description 创建导航菜单
 * @param treeNode 菜单树节点信息
 * @author chaowangbang
 * @since 2017-10-06
 */
Ccay.Layout.createMenuTree = function(node) {
	debugger;
	var nodeLevelClass = ["","nav-second-level","nav-third-level","nav-four-level","nav-five-level","nav-six-level","nav-seven-level","nav-eight-level","nav-nine-level","nav-ten-level"];
	var templet = '<a title="${name}" onclick="Ccay.Layout.menuNodeClick(event,${siteNodeId});" data-treeid="${siteNodeId}" ><i class="fa fa-${faName}"></i><%if(level == 1){%><span class="nav-label">${name}</span><%}else{%>${name}<%}%><%if(hasChildren){%><span class="fa arrow"></span><%}%></a>'
	var html = '<li>' + Ccay.UI.template(templet, node);
	if (node.children) {
		html += '<ul class="nav collapse '+nodeLevelClass[node.level]+'">'
		for (var i = 0, tempNode; tempNode = node.children[i]; i++) {
			html += Ccay.Layout.createMenuTree(tempNode);
		}
		html += '</ul>'
	}
	return html + '</li>';
}
/**
 * @description 菜单单击事件处理
 * @param event 事件
 * @param treeNode 菜单id
 * @author chaowangbang
 * @since 2017-10-06
 */
Ccay.Layout.menuNodeClick=function(event,nodeId){
	//_stopDefasultEvent(event);
	var treeNode = Ccay.Layout.findMenuNodeByAttr(workspaceVO.leftMenuNode,nodeId); 
//	$("#globalloading").remove();
	var Target=Ccay.Layout.Config.LeftMenu.Target,target=treeNode.target,url;
	if(treeNode.url && treeNode.url.length>2){
		//if判断是否为点击节点为当前节点
		if(treeNode.url==window.location.hash){
			Ccay.Page.forward(treeNode.url);
		}else{
			if(target==Target.self){
				if(treeNode.url.indexOf("#!")==0){
					Ccay.Layout.selectNode(treeNode);
					Ccay.Page.forward(treeNode.url.substring(2));
					if($("body").hasClass("body-small")){
						$("body").removeClass("mini-navbar");
					}
					Ccay.Layout.renderTitle(treeNode);
				}else{
					window.location=treeNode.url;
				}
			}else if(target==Target.blank){
				Ccay.Layout.selectMenuByUrl();
				window.open(treeNode.url).focus();
				return;
			}else if(target==Target.frame){
			}else{
				Ccay.Layout.selectMenuByUrl();
				window.open(treeNode.url,target);
				return;
			}
		}
	}
	
}


/**
 * @description 递归通过nodeId获取node对象
 * @param node 当前结点（入口为根节点）
 * @param nodeId 菜单id
 * @author chaowangbang
 * @since 2017-10-06
 */
Ccay.Layout.findMenuNodeByAttr = function(node,attr,attrName){
	var attrName = attrName || "siteNodeId";
	if(node[attrName] === attr){
		return node;
	}
	var child = null;
	if(node.children){
		for (var i= 0, tempNode; tempNode = node.children[i]; i++) {
			var child = Ccay.Layout.findMenuNodeByAttr(tempNode,attr,attrName);
			if(child){
				break;
			}
		}
	}
	return child;
}

/**
 * @description 选择菜单
 * @param nodeId 菜单id
 * @since 2017-10-15
 */
Ccay.Layout.selectNode = function(node){
	Ccay.Layout.navigation.find("ul").removeClass("in");
	var a = $("a[data-treeid='"+node.siteNodeId+"']");
	a.parents("ul").addClass("in");
	Ccay.Layout.navigation.find("li").removeClass("active");
	a.parents("li").addClass("active");
}

/**
 * @description 浏览器的title渲染，可覆盖自定义该方法
 * @param treeNode 菜单树节点信息
 * @since 2017-10-15
 */
Ccay.Layout.renderTitle = function(treeNode){
	document.title = treeNode.name;
};	

/**
 * @description iGrid全屏编辑模式时关闭/刷新浏览器给出警告提示。
 * @return {String}
 */
window.onbeforeunload = function () {
	var $full = $('.ccay-fullscreen-full'), $igrid;
	if ($full.length > 0 ) {
		$igrid = $full.find('.ccay-igrid');
		if ($igrid.length > 0 && $igrid.manager().op.fullOutTip) {
			return $i18n("ccay.common.messag.fullOutTip");
		}
	}
}
